// eslint-disable-next-line @typescript-eslint/no-use-before-define
import AI_MATCH from '@/assets/image/ai_match.png';
import DEL_ICON from '@/assets/image/del_sm.png';
import DOC_ICON from '@/assets/image/doc.png';
import NO_DOC_ICON from '@/assets/image/no_refer_doc.png';
import DataSel from '@/components/DataSel';
import { search } from '@/services/ant-design-pro/api';
import { getFileSize } from '@/utils';
import { FileAddOutlined } from '@ant-design/icons';
import type { TabsProps, UploadProps } from 'antd';
import { Button, Checkbox, Input, message, Modal, Spin, Tabs, Upload } from 'antd';
import mammoth from 'mammoth';
import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import { styles } from './style';

const ReferDoc: React.FC<any> = (props: any) => {
  const { updateReferDoc, contentKey, showReferCheck, updateCheck, historyReference } = props;
  // const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [activeKey, setActiveKey] = useState<string>('1');
  const [checked, setChecked] = useState(true);
  const [doc, setDoc] = useState<string>('');
  const [inputDraft, setInputDraft] = useState<string>('');
  const [wordDraft, setWordDraft] = useState<string>('');
  const [dataDraft, setDataDraft] = useState<string>('');
  const [isOpen, setIsOpen] = useState<boolean>(false);
  const [fileList, setFileList] = useState<any>([]);
  const { TextArea } = Input;
  const { Dragger } = Upload;
  const headerUploadRef = useRef(null);

  const readFileContent = (file: any) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = async (loadEvent: any) => {
        const arrayBuffer = loadEvent.target['result'];
        try {
          const resultObject = await mammoth.extractRawText({ arrayBuffer: arrayBuffer });
          let wordTxt = resultObject.value;
          if (wordTxt.length > 3000) {
            file.fileStatus = '超出3000字限制';
            message.warning(`(${file.name}) 超出3000字限制！`);
            setWordDraft('');
          } else {
            file.fileStatus = 'normal';
            file.title = file.name.split('.')[0];
            file.content = wordTxt;
            setWordDraft(wordTxt);
          }
          resolve(file);
        } catch (error) {
          console.log('=====error======', error);
          file.fileStatus = '文件格式有误';
          message.warning(`(${file.name}) 文件格式有误！`);
          setWordDraft('');
          resolve(file);
        }
      };
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });
  };

  const upLoadProps: UploadProps = {
    name: 'file',
    accept: '.docx, .doc, .md, .txt',
    action: '',
    headers: {},
    maxCount: 1,
    showUploadList: false,
    beforeUpload: () => {
      // return readFileContent(file);
      return false;
    },
    onChange: async (filer: any) => {
      console.log('==filer=', filer);
      if (filer.file?.status !== 'uploading') {
        await readFileContent(filer.file);
        const files = filer.fileList.map((file: any) => {
          if (file.uid === filer.file.uid) {
            file.originFileObj = filer.file;
          }

          return file;
        });
        setFileList(files);
      }
      if (filer.file?.status === 'done') {
        message.success(`${filer.file.name} file uploaded successfully`);
      } else if (filer.file?.status === 'error') {
        message.error(`${filer.file.name} file upload failed.`);
      }
    },
    style: { height: '260px' },
  };

  const selDataDoc = (content: any) => {
    setDataDraft(content);
  };

  const onInputChange = (e: any) => {
    setInputDraft(e.target.value);
  };
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `手动输入`,
      children: (
        <TextArea
          value={inputDraft}
          showCount
          rows={12}
          maxLength={3000}
          placeholder="请输入文档"
          onChange={onInputChange}
          style={{ marginBottom: 16 }}
        />
      ),
    },
    {
      key: '2',
      label: `本地文档`,
      children: (
        <div style={{ background: '#F9FAFC', borderRadius: '6px', border: '1px solid #DBDFEC' }}>
          <Dragger ref={headerUploadRef} {...upLoadProps} style={{ border: 'none' }}>
            {fileList?.length > 0 ? (
              <div style={{ height: '348px', padding: '0 15px' }}>
                {fileList.map((item: any, index: React.Key | null | undefined) => {
                  return (
                    <div key={index} style={styles.fileCard}>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src={DOC_ICON} alt="" width={26} height={26} />
                        <div style={{ marginLeft: '12px' }}>{item?.name.substring(0, 15)}</div>
                        {item?.originFileObj.fileStatus !== 'normal' && (
                          <div style={{ marginLeft: '10px', color: 'red' }}>
                            {item.originFileObj.fileStatus}
                          </div>
                        )}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div style={{ marginRight: '100px' }}>{getFileSize(item?.size)}</div>
                        <img
                          src={DEL_ICON}
                          width={14}
                          height={16}
                          alt=""
                          style={{ cursor: 'pointer' }}
                          onClick={(e) => {
                            e.stopPropagation();
                            const fileListCopy = [...fileList];
                            fileListCopy.splice(index, 1);
                            if (headerUploadRef.current) {
                              headerUploadRef.current.fileList.splice(index, 1);
                            }
                            setFileList(fileListCopy);
                          }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div>
                <p className="ant-upload-drag-icon" style={{ marginTop: '70px', fontSize: '18px' }}>
                  <FileAddOutlined />
                </p>
                <p className="ant-upload-text" style={{ marginBottom: '70px', fontSize: '14px' }}>
                  点击选择文档，或直接拖拽文档到此
                </p>
              </div>
            )}
          </Dragger>
        </div>
      ),
    },
    {
      key: '3',
      label: `从知识库选择`,
      children: <DataSel selDataDoc={selDataDoc}></DataSel>,
    },
  ];

  const tabChange = (e: any) => {
    setActiveKey(e);
  };

  const handleCancel = () => {
    setLoading(false);
    setInputDraft('');
    setWordDraft('');
    setFileList([]);
    setIsOpen(false);
  };

  const handleOk = async () => {
    const wordTxt = activeKey === '1' ? inputDraft : activeKey === '2' ? wordDraft : dataDraft;
    if (wordTxt.length > 3000) {
      message.error('目前只支持上传3000字以内的文案');
      return;
    }
    setLoading(true);
    setDoc(wordTxt);
    updateReferDoc(wordTxt || '');
    // const res = await uploadFile();
    handleCancel();
  };
  useEffect(() => {
    // if (historyReference) {
    //   setDoc(historyReference);
    //   updateReferDoc(historyReference || '');
    // }
    // 读取版本记录时，参考文档有可能是空的
    setDoc(historyReference);
    // updateReferDoc(historyReference || '');
  }, [historyReference]);
  const handleSearch = async () => {
    setLoading(true);
    try {
      if (!contentKey) {
        message.error('请输入你的指令');
        return;
      }
      const res = await search({
        content: contentKey,
      });
      if (res.code === 0) {
        setDoc(res?.data.result);
        updateReferDoc(res?.data.result);
      }
      // if (res?.success && res?.result) {
      //   setDoc(res?.result);
      //   updateReferDoc(res?.result);
      // }
    } catch {
      //
    } finally {
      setLoading(false);
    }
  };

  const checkDoc = () => {
    setChecked(!checked);
    updateCheck(!checked);
  };

  return (
    <div>
      <Spin spinning={loading}>
        <div
          style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'space-between',
            fontSize: '11px',
          }}
        >
          <div style={{ display: 'flex', flexDirection: 'row' }}>
            <Button
              style={{
                marginRight: 10,
                height: '27px',
                display: 'flex',
                alignItems: 'center',
                background: '#F9FAFF',
                border: '1px solid #E7EAF7',
                borderRadius: '4px',
                boxShadow: 'none',
                fontSize: '11px',
              }}
              onClick={() => setIsOpen(true)}
            >
              <img
                src={DOC_ICON}
                alt=""
                height="17px"
                width="17px"
                style={{ paddingRight: '2px' }}
              />
              选择参考文档
            </Button>
            <Button
              style={{
                marginRight: 10,
                height: '27px',
                display: 'flex',
                alignItems: 'center',
                background: '#FFFBF9',
                borderRadius: '4px',
                border: '1px solid #FFE6D2',
                boxShadow: 'none',
                fontSize: '11px',
              }}
              onClick={handleSearch}
            >
              <img
                src={AI_MATCH}
                alt=""
                height="17px"
                width="17px"
                style={{ marginRight: '2px' }}
              />
              AI智能匹配文档
            </Button>
          </div>
          {showReferCheck && (
            <div style={styles.cbutton}>
              <Checkbox
                checked={checked}
                onChange={(e) => checkDoc(e)}
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  minWidth: '130px',
                  fontSize: '11px',
                }}
              >
                根据参考文档生成
              </Checkbox>
            </div>
          )}
        </div>
        <div>
          {doc && doc.length > 0 ? (
            <div className="referContent">
              <div>{doc}</div>
            </div>
          ) : (
            <div style={{ marginTop: '28px' }} className="noDocBox">
              <img src={NO_DOC_ICON} alt="" height="220px" width="258px" />
              <div style={styles.noDoc}>你可以选择参考文档，文章生成更精准～</div>
            </div>
          )}
        </div>
      </Spin>
      <Modal
        title="选择参考文档"
        open={isOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={'680px'}
        footer={[
          <div
            key="1"
            style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
          >
            {/* <Checkbox checked={checked} onChange={() => setChecked(!checked)}>打开作为参考文档使用</Checkbox> */}
            <div></div>
            <div style={{ gap: '20px' }}>
              <Button onClick={handleCancel} style={styles.button}>
                取消
              </Button>
              <Button
                type="primary"
                loading={loading}
                onClick={handleOk}
                style={{ ...styles.button, background: '#397BFF' }}
              >
                确定
              </Button>
            </div>
          </div>,
        ]}
      >
        <Tabs defaultActiveKey="1" items={items} activeKey={activeKey} onChange={tabChange}></Tabs>
      </Modal>
    </div>
  );
};

export default ReferDoc;
